package com.xp.tinyurl.common.util;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Description http client utils
 * @Author chengguo.pei
 * @Date 2021/9/22 15:36
 */
@Slf4j
public class HttpClientUtils {

    public static <T> T post(String url, Map<String, Object> reqParams, Class<T> resClazz) throws IOException{
        CloseableHttpResponse response = post(url, reqParams);
        if(!isOk(response)){
            return null;
        }
        return buildRes(response, resClazz);
    }

    public static <T> T get(String url, Class<T> resClazz) throws IOException{
        CloseableHttpResponse response = get(url);
        if(!isOk(response)){
            return null;
        }
        return buildRes(response, resClazz);
    }

    /**
     * 处理结果
     * @param httpResponse
     * @param resClazz
     * @param <T>
     * @return
     * @throws IOException
     */
    public static <T> T buildRes(CloseableHttpResponse httpResponse, Class<T> resClazz) throws IOException {
        HttpEntity httpEntity = httpResponse.getEntity();
        // 输出请求结果
        String res = EntityUtils.toString(httpEntity);
        return JSONObject.parseObject(res, resClazz);
    }

    /**
     * 响应是否OK
     * @param httpResponse
     * @return
     */
    public static boolean isOk(CloseableHttpResponse httpResponse){
        return httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK;
    }


    public static CloseableHttpResponse post(String url, Map<String, Object> reqParams) throws IOException{
        // 创建 HttpPost 参数
        HttpPost httpPost = new HttpPost(url);
        List<BasicNameValuePair> params = new ArrayList<>();
        reqParams.forEach((k, v) -> {
            params.add(new BasicNameValuePair(k, String.valueOf(v)));
        });
        //build client
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse httpResponse = null;
        try {
            // 设置 HttpPost 参数
            httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
            return httpClient.execute(httpPost);
        } finally {
            try {
                if (httpResponse != null) {
                    httpResponse.close();
                }
            } catch (Exception e) {
                log.error("关闭httpResponse异常", e);
            }
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (Exception e) {
                log.error("关闭httpClient异常", e);
            }
        }
    }

    public static CloseableHttpResponse get(String url) throws IOException{
        // 创建 HttpPost 参数
        HttpGet httpGet = new HttpGet(url);
        //build client
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse httpResponse = null;
        try {
            // 设置 HttpPost 参数
            return httpClient.execute(httpGet);
        } finally {
            try {
                if (httpResponse != null) {
                    httpResponse.close();
                }
            } catch (Exception e) {
                log.error("关闭httpResponse异常", e);
            }
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (Exception e) {
                log.error("关闭httpClient异常", e);
            }
        }
    }

}
